package com.thinking.project.monitorserver.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinking.project.monitorserver.pojo.Worker;
import com.thinking.project.monitorserver.service.WorkerService;
import com.thinking.project.monitorserver.util.JwtTokenUtil;
import com.thinking.project.monitorserver.util.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Description 功能描述：  验证响应的 token值是否合法  采用 springMVC
 * @Author tangsixiang@163.com
 * @DATE 2019/6/24 11:04
 * @Version 1.0
 **/
@Component
@Slf4j
public class TokenHandler implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate redisTemplate;


    /***
     *  通过拦截请求方法 在此处判断 1、 token值是否有效
     *                            2、 请求连接是否有权限
     *
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        ResponseData responseData = ResponseData.ok();
        String token = request.getHeader("Authorization");
        //token不存在
          log.info( request.getRemoteHost());
        if (null != token) {
            //解密token后的loginId与用户传来的loginId不一致，一般都是token过期
            Worker login = JwtTokenUtil.verifyToken(token, Worker.class);
            //request.setAttribute("loginId",login.getWorkerId());//添加到数据请求属性中后一段业务做判断
            if (null != login && redisTemplate.hasKey(String.format("user:login:mark:[%s]", login.getWorkerId()))) {

                //增加数据权限业务判断
                // 通过角色 获取请求资源地址
                // 数据验证正常
                return true;
            } /*else if (null != login) {
                //token有效值 客户主动推出登录--此token失效!
                ResponseData.customerError().putDataValue("mess", "token值已过期或失效，请重新获取");
            }*/ else {
                // 非法token值入侵
                responseData = ResponseData.customerError().putDataValue("mess", "token值已过期或失效，请重新获取");
            }
        } else {
            responseData = ResponseData.unauthorized().putDataValue("mess", "请仔细阅读接口规范！");
        }
        responseMessage(response, response.getWriter(), responseData);
        return false;
    }

    //请求不通过，返回错误信息给客户端
    private void responseMessage(HttpServletResponse response, PrintWriter out, ResponseData responseData) throws Exception {
        response.setCharacterEncoding("utf-8");
        responseData = ResponseData.forbidden();
        response.setContentType("application/json; charset=utf-8");
        String json = new ObjectMapper().writeValueAsString(responseData);
        out.print(json);
        out.flush();
        out.close();
    }


}
